/*
 * File:    TimeUnitParser.java
 * Created: 07-Nov-2007
 *
 * by Kenji Hollis <kenji@bitgatesoftware.com>
 * Released under the Creative Commons License version 2.5
 */

package com.bitgate.util.uom;

import java.util.ArrayList;

/**
 * This is a helper class that takes a well formatted string containing several time string objects, and
 * converts it into a final number in milliseconds.  The string can be well formatted using spaces between each
 * object, commas, or tabs.
 * 
 * @author Kenji Hollis &lt;kenji@bitgatesoftware.com&gt;
 * @since 0.1
 */
public class TimeUnitParser {
	
	/**
	 * Takes a formatted string, parses each time unit from it, and returns a final value.
	 * 
	 * @param str <code>String</code> containing the string to parse.
	 * @return <code>long</code> containing the final value.
	 */
	public static long parse(String str) {
		String strToParse = str.replaceAll(" ", "").replaceAll(",", "").replaceAll("\t", "");
		ArrayList<String> parsedUnits = new ArrayList<String>();
		int strLength = strToParse.length();
		int lastKnownPosition = 0;
		
		for(int i = 0; i < strLength; i++) {
			if (!Character.isDigit(strToParse.charAt(i))) {
				i++;
				parsedUnits.add(strToParse.substring(lastKnownPosition, i));
				lastKnownPosition = i;
				continue;
			}
		}
		
		if (lastKnownPosition != strLength) {
			parsedUnits.add(strToParse.substring(lastKnownPosition, strLength));
		}
		
		long returnValue = 0L;
		
		for(String parseUnit : parsedUnits) {
			returnValue += TimeUnit.DEFAULT.parse(parseUnit);
		}
		
		return returnValue;
	}
}